# 个人中心
from django.conf import settings
from rest_framework import status, mixins
from rest_framework.generics import UpdateAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_mongoengine.generics import RetrieveUpdateAPIView
from rest_framework_mongoengine.viewsets import ModelViewSet

from apps.person.models import User
from apps.person.serializers import PersonSerializer, UploadSerializer
# from apps.person.serializers import UploadSerializer

class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = PersonSerializer

    def retrieve(self, request, *args, **kwargs):
        serializer = self.serializer_class(request.user)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        serializer = self.serializer_class(request.user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

class PassWord(APIView):

    def put(self, request):
        # 获取参数
        password = request.data["password"]
        # 获得请求用户
        user = User.objects.get(id=request.user.id)
        if len(password) > 20 or len(password) < 8:
            raise Exception("密码长度需要8到20位")
        # 修改密码为新密码
        user.set_password(password)
        user.save()
        # 返回数据
        return Response(status=status.HTTP_202_ACCEPTED)

class UserLike(mixins.CreateModelMixin,
              mixins.DestroyModelMixin,
              mixins.ListModelMixin,
              GenericViewSet):
    queryset = User.objects.all()
    serializer_class = PersonSerializer
    lookup_value_regex = '\d+'


class UPloadavatarView(ModelViewSet):
    # 指定视图所使用的序列化器类
    serializer_class = UploadSerializer
    # 指定视图所使用的查询集
    queryset = User.objects.all()

    # # 重写拓展类的保存业务逻辑
    def create(self, request, *args, **kwargs):
        from fdfs_client.client import Fdfs_client
        # 创建FastDFS连接对象
        client = Fdfs_client(
            '/home/ubuntu/Desktop/ten/ten/utils/fastdfs/client.conf')
        # 获取前端传递的image文件
        data = request.FILES.get('img')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(data.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']

        # 修改图片
        user = User.objects.filter(id=request.user.id).update(avatar=image_url)
        # 返回结果
        return Response(
            {
                'user':user,
                'imgurl': settings.FDFS_URL + image_url
            },
            status=201  # 前端需要接受201状态
        )










